/**
 * @author:曹仁道 2016年9月1日 上午10:26:04
 * @描述：
 */
var ZFTree = {
		//这里用了局部动态加载js和css，建议index中的js和css也采用动态加载，初始值加载主要部分，其他的在需要的时候再加载
	loadJs : function(jsUrls, fnBack) {
		for(var i=0;i<jsUrls.length;i++){
			var ga = document.createElement('script');
			ga.type = 'text/javascript';
			ga.async = true;
			ga.src = jsUrls[i];
			var s = document.getElementsByTagName('script')[0];
			s.parentNode.insertBefore(ga, s);
		}
		fnBack();
	},
	loadCss : function(cssUrls, fnBack) {
		for(var i=0;i<cssUrls.length;i++){
			var ga = document.createElement('link');
			ga.rel = 'stylesheet';
			ga.async = true;
			ga.href = cssUrls[i];
			var s = document.getElementsByTagName('link')[0];
			s.parentNode.insertBefore(ga, s);
		}
		fnBack();
	},
	loadInit : function(fnBack) {
		var jsUrls=[];
		//jsUrls.push("static/libs/bootstrap-treeview/bootstrap-treeview.min.js");
		jsUrls.push("static/libs/ztree/jquery.ztree.all.min.js");
		ZFTree.loadJs(jsUrls,function(){
			var cssUrls=[];
			cssUrls.push("static/libs/ztree/css/metroStyle/metroStyle.css");
			ZFTree.loadCss(cssUrls,	function(){
				setTimeout(function(){fnBack();},500);
			});
		});
	},
	zTreeObj:null,
	addChildNodeName:"",
	editNodeName:"",
	removeNodeName:"",
	initTree:function(nodes,treeEle,choseType,onclickName,isRightClick,open,asyncUrl){//choseType:checkbox;radio;none(默认)
		if(zfesUtil.isStrNull(choseType)||(choseType!="checkbox"&&choseType!="radio")){
			choseType="none";
		}
		if(zfesUtil.isStrNull(isRightClick)){
			isRightClick=false;
		}
		var isOnClick=true;
		if(zfesUtil.isStrNull(onclickName)||onclickName=="false"||onclickName=="true"||onclickName=="none"
			||onclickName=="function"||onclickName==""){//这里表示不能用相关JavaScript的关键字作为方法名
			isOnClick=false;
		}
		var setting = {
				async:{
					enable: true,
					url:asyncUrl,
					autoParam:["id=pid"],
					otherParam:{},
					dataFilter:function(treeId, parentNode, responseData){
						 if (responseData) {
					      for(var i =0; i < responseData.length; i++) {
					        responseData[i].click = onclickName+"('"+responseData[i].id+"')";
					      }
					    }
					    return responseData;
					}
				},
				check: {
					enable: choseType=="none"?false:true,
					autoCheckTrigger: true,
					chkStyle: choseType
				},
				edit: {
					enable: false
				},
				view: {
					fontCss: {"font-size":"14px"}
				},
				data: {
					simpleData: {
						enable: true,
						idKey: "id",
						pIdKey: "pId",
						rootPId: "-1"
					}
				},
				callback: {
					onRightClick: isRightClick?ZFTree.rightClick:null,
					//beforeClick:ZFTree.onClick,
					onAsyncSuccess:function(){
						setTimeout(function(){
							var treeObj = $.fn.zTree.getZTreeObj(treeEle);
							var nodes = treeObj.getNodes();
							if (nodes.length>0) {
								treeObj.expandNode(nodes[0], true, false, true);
							}
						},50);
						
						
						
					}
				}
		};
		if(zfesUtil.isStrNull(nodes)||!zfesUtil.isStrNull(asyncUrl)){
			nodes =null;
		}else{
			if(!zfesUtil.isStrNull(open)){
				open=parseInt(open);
			}else{
				open=0;
			}
			for(var i=0;i<nodes.length;i++){
					var node=nodes[i];
					if(isOnClick){
						node.click=onclickName+"('"+node.id+"')";
					}
					if(i<=open){
						node.open=true;
					}
					nodes.splice(i,1,node);
			}
		}
		ZFTree.loadInit(function(){
			//清空km-tree
			$("#"+treeEle).html("");
			$("#"+treeEle).addClass("ztree");
			ZFTree.zTreeObj = $.fn.zTree.init($("#"+treeEle), setting, null);
		});
		return ZFTree.zTreeObj;
	},
	onClick:function(treeId, treeNode, clickFlag){
		var treeObj = $.fn.zTree.getZTreeObj(treeId);
		var nodes = treeObj.getSelectedNodes();
		if (nodes.length>0) {
			treeObj.reAsyncChildNodes(nodes[0], "refresh");
		}
	},
	rightClick:function(event, treeId, treeNode){
		var nodeId=treeNode.id;
		nodeId=$.trim(nodeId);
	//创建隐藏右键域
		var $content=$("body").find("#context-menu");
		if($content.length<1){
			var rightTag="<div id='context-menu' style='display:none;position:absolute;'><ul class='dropdown-menu'>";
			if(!zfesUtil.isStrNull(ZFTree.addChildNodeName)){
				rightTag+="<li id='menu-add'><a onclick="+ZFTree.addChildNodeName+"('"+nodeId+"');>添加子节点</a></li>";
			}
			if(!zfesUtil.isStrNull(ZFTree.editNodeName)){
				rightTag+="<li id='menu-edit'><a onclick="+ZFTree.editNodeName+"('"+nodeId+"');>修改</a></li>";
			}if(!zfesUtil.isStrNull(ZFTree.removeNodeName)){
				rightTag+="<li id='menu-del'><a  onclick="+ZFTree.removeNodeName+"('"+nodeId+"');>删除节点</a></li>";
			}
			rightTag+="</ul></div>";
			$("body").append(rightTag);
		}else{
			//$("body").find("#context-menu").find("#menu-add").find("a").bind("onclick",ZFTree.addChildNodeName+"('"+nodeId+"')");
			$("body").find("#context-menu").find("li").each(function(){
				var idAttr=$(this).attr("id");
				if(idAttr=="menu-add"){
					$(this).find("a").attr("onclick",ZFTree.addChildNodeName+"('"+nodeId+"')");
				}else if(idAttr=="menu-edit"){
					$(this).find("a").attr("onclick",ZFTree.editNodeName+"('"+nodeId+"')");
				}else if(idAttr=="menu-del"){
					$(this).find("a").attr("onclick",ZFTree.removeNodeName+"('"+nodeId+"')");
				}
			});
		}
		//console.log("event:"+event+",x："+event.clientX+",y:"+event.clientY+",scrollTop:"+document.body.scrollTop);
		var x=event.clientX;
		var y=event.clientY+document.body.scrollTop;
		if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
			//zTree.cancelSelectedNode();
			ZFTree.showRMenu("root", x, y);
		} else if (treeNode && !treeNode.noR) {
			ZFTree.zTreeObj.selectNode(treeNode);
			ZFTree.showRMenu("node", x, y);
		}
	},
	showRMenu:function(type, x, y) {
		$("#context-menu ul").show();
		if (type=="root") {
			$("#menu-edit").hide();
			$("#menu-del").hide();
		} else {
			$("#menu-add").show();
			$("#menu-edit").show();
			$("#menu-del").show();
		}
		$("#context-menu").css({"top":y+"px", "left":x+"px", "display":"block"});
		$("body").bind("mousedown", ZFTree.onBodyMouseDown);
		//同时绑定单击事件
		$("body").find("#context-menu").find("li").each(function(){
			$(this).bind("click",ZFTree.onMenuLiClick);
		});
	},
	hideRMenu:function () {
		if ($("#context-menu")) {
			$("#context-menu").css({"display": "none"});
		}
		$("body").unbind("mousedown", ZFTree.onBodyMouseDown);
	//同时绑定单击事件
		$("body").find("#context-menu").find("li").each(function(){
			$(this).unbind("click",ZFTree.onMenuLiClick);
		});
	},
	onBodyMouseDown:function (event){
		if (!(event.target.id == "context-menu" || $(event.target).parents("#context-menu").length>0)) {
			$("#context-menu").css({"display" : "none"});
		}
	},
	onMenuLiClick:function(event){
		$("#context-menu").css({"display" : "none"});
	},
	getTreeNodes:function(eleId){
		var treeObj = $.fn.zTree.getZTreeObj(eleId);
		var nodes = treeObj.transformToArray(treeObj.getNodes());
		return nodes;
	},
	getTreeNodesParam:function(eleId,proName,proValue,pid){
		var treeObj = $.fn.zTree.getZTreeObj(eleId);
		if(zfesUtil.isStrNull(pid)){
			pid=null
		}
		var nodes = treeObj.transformToArray(treeObj.getNodesByParam(proName, proValue, pid));
		return nodes;
	},
	getTreeNodeById:function(eleId,id){
		var treeObj = $.fn.zTree.getZTreeObj(eleId);
		var nodes = treeObj.transformToArray(treeObj.getNodesByParam("id", id, null));
		return nodes[0];//仅仅返回当前节点，子节点不返回
	},
	getTreeNodeByCode:function(eleId,code){
		var treeObj = $.fn.zTree.getZTreeObj(eleId);
		var nodes = treeObj.transformToArray(treeObj.getNodesByParam("code", code, null));
		return nodes[0];//仅仅返回当前节点，子节点不返回
	},
	reloadTree:function(eleId){
		var treeObj = $.fn.zTree.getZTreeObj(eleId);
		treeObj.refresh();
	},
	refreshTreeAll:function(eleId,param){
		var treeObj = $.fn.zTree.getZTreeObj(eleId);
		treeObj.setting.async.otherParam=param;
		treeObj.reAsyncChildNodes(null, "refresh");
	},
	refreshTreeSelectNode:function(eleId){
		var treeObj = $.fn.zTree.getZTreeObj(eleId);
		var nodes = treeObj.getSelectedNodes();
		if (nodes.length>0) {
			treeObj.reAsyncChildNodes(nodes[0], "refresh");
		}
	},
	getCheckedNodes:function(eleId){
		var treeObj = $.fn.zTree.getZTreeObj(eleId);
		var nodes = treeObj.getCheckedNodes();
		return nodes;
	},
	getCheckedNode:function(eleId){
		return ZFTree.getCheckedNodes(eleId)[0];
	},
	init:function(){
		var $kmSelect=$("body").find("km-tree");
		$kmSelect.each(function(){
			var treeMenuDiv=$(this).closest("div");
			if(treeMenuDiv.length>0){
				var treeMenuId=treeMenuDiv.attr("id");
				var url=$(this).attr("url");
				var param=$(this).attr("param");
				var chooseType=$(this).attr("chooseType");
				var isRightClick=$(this).attr("isRightClick");
				var onclick=$(this).attr("onclick");
				var openNum=$(this).attr("openNum");
				var host=$(this).attr("host");
				if(!zfesUtil.isStrNull(isRightClick)){
					if(isRightClick=="false"){
						isRightClick=false;
					}else if(isRightClick=="true"){
						isRightClick=true;
						ZFTree.addChildNodeName=$(this).attr("addChildNodeName");
						ZFTree.editNodeName=$(this).attr("editNodeName");
						ZFTree.removeNodeName=$(this).attr("removeNodeName");
					}else{
						isRightClick=false;
					}
				}else{
					isRightClick=false;
				}
				var onclickName="";
				if(!zfesUtil.isStrNull(onclick)){
					onclickName=onclick;
				}
				if(zfesUtil.isStrNull(url)){
					alertMsg.error("url是必须的，否则无法获取到树数据！ ");;
				}
				var subParam={};
				if(!zfesUtil.isStrNull(param)){
					var params=param.split(",");
					if(params.length>0){
						for(var i=0;i<params.length;i++){
							var key=params.split("=")[0];
							var value=params.split("=")[1];
							subParam.key=value;
						}
					}
				}
				//zfesAjax.ajax(host+url,subParam, function(data){
					ZFTree.initTree(null,treeMenuId,chooseType,onclickName,isRightClick,openNum,url);
				//});
			}
		});
	}
}